// const wxRequest = require('../../utils/request')

const promiseify = require('../../utils/promiseify')
const wxRequest = promiseify(wx.request)
const wxOpenSetting = promiseify(wx.openSetting)

Page({
  data: {
    tempFilePath: '',
  },

  async request() {
    let res = await wxRequest({
      url: 'http://47.98.187.80:5000/api/getlunbo',
      method: 'get'
    })
    console.log(res.data)
  },

  selectMedia() {
    let _this = this

    // 选择图片
    wx.chooseMedia({
      mediaType: ['image'], // 仅支持图片媒体
      sourceType: ['camera'], // 仅能通过拍摄获取图片
      success(res) {
        _this.setData({
          tempFilePath: res.tempFiles[0].tempFilePath
        })

        // 保存到相册，判断用户是否具有某个权限
        _this.savePhoto()
      }
    })

  },

  // 保存图片
  savePhoto() {
    const _this = this
    // 保存到相册，判断用户是否具授权某个权限
    wx.getSetting({
      success(res) {
        // 用户没有此权限
        if (!res.authSetting['scope.writePhotosAlbum']) {
          console.log('用户没有此权限')
          // 弹框申请对应的权限
          _this.accessAuth()
        } else {
          // 下载图片
          _this.downloadPhoto()
        }
      }
    })
  },

  // 申请权限
  accessAuth() {
    const _this = this
    wx.authorize({
      scope: 'scope.writePhotosAlbum',
      success() {
        console.log('申请成功')
        _this.downloadPhoto()
      },
      fail() {
        console.log('申请失败')
        _this.openSettingPage()
      }
    })
  },

  // 模态框去打开设置页面
  openSettingPage() {
    const _this = this
    wx.showModal({
      title: '权限',
      content: '申请权限失败，需要设置页面开启哦',
      showCancel: true,
      complete: async (res) => {
        if (res.confirm) {
          // 打开设置页面
          const res = await wxOpenSetting()
          // 获取用户是否有没有在设置页面开启
          if (res.authSetting['scope.writePhotosAlbum']) {
            _this.downloadPhoto()
          } else {
            // 不开启，递归调用自己
            _this.openSettingPage()
          }

        }
      }
    })
  },

  downloadPhoto() {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.tempFilePath
    })
  },
})